<html xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <title>资源定义列表</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <script src="../../static/react/react.development.js" type="text/javascript"></script>
    <script src="../../static/react/react-dom.development.js" type="text/javascript"></script>
    <script src="../../static/react/moment-with-locales.min.js" type="text/javascript"></script>
    <script src="../../static/react/babel.min.js" type="text/javascript"></script>
    <!-- antd -->
    <link href="../../static/react/antd/antd.min.css" rel="stylesheet" type="text/css"/>
    <script src="../../static/react/antd/antd-with-locales.min.js" type="text/javascript"></script>
    <!-- axios -->
    <script src="../../static/react/axios.min.js" type="text/javascript"></script>
    <script src="../../static/react/qs.js" type="text/javascript"></script>
    <script src="../../static/react/lodash.min.js" type="text/javascript"></script>
    <script src="../../static/react/request.js" type="text/javascript"></script>
    <script src="../../ffres/dict/all.js" type="text/javascript"></script>
    <link href="../../static/react/common.css" rel="stylesheet" type="text/css"/>
    <style type="text/css">
        .button-div{
            text-align: center;
        }

        .button-div button{
            margin: 20px;
        }

        .logo {
            font-size: 16px;
            height: 32px;
            background: #dbdee3;
            color: #585454;
            text-align: center;
            line-height: 32px;
            overflow: hidden;
        }

        .form-title {
            font-size: 16px;
            height: 32px;
            margin-bottom: 10px;
            padding-left: 16px;
            background: #e0e2e7;
            color: #585454;
            line-height: 32px;
            overflow: hidden;
        }

    </style>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
    const baseURL = '../../'
    const {Layout, Menu, Tabs, Row, Col, Form, Input, Select, DatePicker, Button, Table, Modal, message} = antd
    const {Header, Content, Footer} = Layout


    class Root extends React.Component {
        constructor(props) {
            super(props)
            // 在构造器中获取引用实例
            this.resFormRefValue = React.createRef()
            this.resModelRefValue = React.createRef()

            this.actFormRefValue = React.createRef()
            this.actModelRefValue = React.createRef()

            this.getTreeResource = this.getTreeResource.bind(this)
            this.doNodeClick = this.doNodeClick.bind(this)
            this.recursiveMap = this.recursiveMap.bind(this)
            this.createTreeMenu = this.createTreeMenu.bind(this)
            this.windowResize = this.windowResize.bind(this)
            this.doResAdd = this.doResAdd.bind(this)
            this.doResUpdate = this.doResUpdate.bind(this)
            this.doResDelete = this.doResDelete.bind(this)
            this.doActAdd = this.doActAdd.bind(this)
            this.doActUpdate = this.doActUpdate.bind(this)
            this.doActDelete = this.doActDelete.bind(this)
            this.handleModelClose = this.handleModelClose.bind(this)
            this.handleModelOk = this.handleModelOk.bind(this)
            this.reset = this.reset.bind(this)
            this.tableSelect = this.tableSelect.bind(this)
            this.state = {
                tree: [],
                loading: "",
                actShow: false,
                resShow:false,
                list: [],
                pageInfo: {
                    page: 1,
                    size: 20,
                    total: 0,
                },
                modelTitle: "",
                opType: "", // 操作类型
                rowSelection: null,
                selectedRowKeys: []
            }
        }

        reset() {
            this.resFormRefValue.current.resetFields()
            this.actFormRefValue.current.resetFields()
        }

        getTreeResource() {
            const self = this
            API.request({
                baseURL: baseURL,
                method: "post",
                url: "api/s/resource/all/root"
            }).then(function (data) {
                let tree = data.map(function (node, index) {
                    return {
                        name: node.text,
                        id: node.id,
                        children: node.children.map(function (chindVal) {
                            return self.recursiveMap(chindVal)
                        })
                    }
                });
                self.setState({"tree": tree})
            })
        }

        recursiveMap(node) {
            return {
                name: node.text,
                id: node.id,
                parentId: node.parentId,
                children: node.children && node.children.length > 0 ? node.children.map(this.recursiveMap) : []
            }
        }

        createTreeMenu(menu) {
            if (menu.children && menu.children.length > 0) {
                return (
                    <Menu.SubMenu key={menu.id} title={<span id={menu.id} onClick={this.doNodeClick}>{menu.name}</span>}>
                        {
                            menu.children.map((menu, index) => {
                                if (menu.children && menu.children.length > 0) {
                                    return this.createTreeMenu(menu)
                                } else {
                                    return <Menu.Item key={menu.id}><span id={menu.id} onClick={this.doNodeClick}>{menu.name}</span></Menu.Item>
                                }
                            })
                        }
                    </Menu.SubMenu>
                )
            } else {
                return <Menu.Item key={menu.id}><span id={menu.id} onClick={this.doNodeClick}>{menu.name}</span></Menu.Item>
            }
        }

        doResAdd() {
            const parentid=this.resFormRefValue.current.getFieldValue("resourceid")
            const self=this
            if(parentid!=null){
                this.setState({resShow: true,actShow: false,modelTitle: "资源菜单新增", opType: "res-add"});
                setTimeout(() => this.resModelRefValue.current.setFieldsValue({parentid:parentid}), 50)
            }else{
                Modal.confirm({
                    title: '尚未选择上级菜单',
                    content: '是否新增一级菜单吗？',
                    okText: '确认',
                    cancelText: '取消',
                    onOk() {
                        self.setState({resShow: true,actShow: false,modelTitle: "资源菜单新增", opType: "res-add"});
                        setTimeout(() => self.resModelRefValue.current.setFieldsValue({parentid:"root"}), 50)
                    },
                });
            }
        }

        doResUpdate() {
            const row=this.resFormRefValue.current.getFieldValue()
            const self=this
            if(row!=null){
                API.request({
                    baseURL: baseURL,
                    method: "put",
                    url: "api/s/resource",
                    data: row,
                }).then(function (data) {
                    message.success("成功修改数据!")
                    self.getTreeResource()
                })
            }
        }

        doResDelete() {
            const self = this
            const row=this.resFormRefValue.current.getFieldValue()
            if (row!=null) {
                Modal.confirm({
                    title: '删除提示',
                    content: '你确定要删除这条记录？',
                    okText: '确认',
                    cancelText: '取消',
                    onOk() {
                        return new Promise((resolve, reject) => {
                            API.request({
                                baseURL: baseURL,
                                method: "delete",
                                url: "api/s/resource",
                                data: row,
                            }).then(function (data) {
                                message.success("记录删除成功!")
                                self.resFormRefValue.current.resetFields()
                                self.getTreeResource()
                                resolve()
                            })
                        });
                    },
                });
            }
        }

        doActAdd() {
            this.setState({resShow: false,actShow:true, modelTitle: "资源菜单新增", opType: "act-add"});
            setTimeout(() => this.actModelRefValue.current.resetFields(), 50)
        }

        doActUpdate() {
            this.setState({resShow: false,actShow:true, modelTitle: "资源菜单修改", opType: "act-update"});
            setTimeout(()=>{
                this.actModelRefValue.current.setFieldsValue(this.state.rowSelection)
            }, 50)
        }

        doActDelete() {
            const self = this
            if (self.state.rowSelection) {
                Modal.confirm({
                    title: '删除提示',
                    content: '你确定要删除这条记录？',
                    okText: '确认',
                    cancelText: '取消',
                    onOk() {
                        return new Promise((resolve, reject) => {
                            API.request({
                                baseURL: baseURL,
                                method: "delete",
                                url: "api/s/resourceaction",
                                data: self.state.rowSelection,
                            }).then(function (data) {
                                message.success("记录删除成功!")
                                self.setState({loading: false, actShow: false});
                                self.getTreeResource()
                            })
                        });
                    },
                });
            }
        }


        windowResize() {
            let iframeHeight = window.innerHeight - 40 - 16
            this.setState({
                iframeHeight: iframeHeight
            })
        }

        doNodeClick(e) {
            const self = this
            if(e.currentTarget.parentElement.className=="ant-menu-submenu-title"){
                e.stopPropagation();
            }
            API.request({
                baseURL: baseURL,
                method: "GET",
                url: "api/s/resource/"+e.currentTarget.id,
                data: null,
            }).then(function (data) {
                setTimeout(()=>{
                    self.resFormRefValue.current.setFieldsValue(data.rows)
                }, 50)
            })
            API.request({
                baseURL: baseURL,
                method: "post",
                dataType:"form",
                url: "api/s/resourceactions",
                data: Qs.stringify({resourceid:e.currentTarget.id})
            }).then(function(data){
                self.setState({
                    list: data.rows.map(function(item, index){ return {...item, key: index}})
                })
            })
        }

        tableSelect(selectedRowKeys, selectedRows) {
            if (selectedRows && selectedRows.length > 0) {
                this.setState({
                    selectedRowKeys,
                    rowSelection: selectedRows[0]
                })
            }
        }

        handleModelClose() {
            this.setState({
                resShow: false,
                actShow:false
            })
        }

        handleModelOk() {
            const self = this
            const {opType} = self.state
            self.setState({
                loading: true
            })
            if (opType == "res-add") {
                self.resModelRefValue.current.validateFields().then(function (values) {
                    API.request({
                        baseURL: baseURL,
                        method: "post",
                        url: "api/s/resource",
                        data: values
                    }).then(function (data) {
                        message.success("操作成功");
                        self.setState({loading: false, resShow: false});
                        self.getTreeResource()
                    }).catch(function (error) {
                        message.warning("操作失败");
                        self.setState({loading: false});
                    })
                }).catch(function (errorInfo) {
                    self.setState({loading: false})
                })
            } else if (opType == "act-add") {
                self.actModelRefValue.current.validateFields().then(function (values) {
                    API.request({
                        baseURL: baseURL,
                        method: "post",
                        url: "api/s/resourceaction",
                        data: values
                    }).then(function (data) {
                        message.success("操作成功");
                        self.setState({loading: false, actShow: false});
                        self.getTreeResource()
                    }).catch(function (error) {
                        message.warning("操作失败");
                        self.setState({loading: false});
                    })
                }).catch(function (errorInfo) {
                    self.setState({loading: false})
                })
            }else if(opType == "act-update") {
                self.actModelRefValue.current.validateFields().then(function (values) {
                    API.request({
                        baseURL: baseURL,
                        method: "put",
                        url: "api/s/resourceaction",
                        data: values
                    }).then(function (data) {
                        message.success("操作成功");
                        self.setState({loading: false, actShow: false});
                        self.getTreeResource()
                    }).catch(function (error) {
                        message.warning("操作失败");
                        self.setState({loading: false});
                    })
                }).catch(function (errorInfo) {
                    self.setState({loading: false});
                })
            } else {
                self.setState({loading: false, actShow: false})
            }
        }

        componentDidMount() {
            this.getTreeResource()
            this.windowResize()
            window.addEventListener('resize', this.windowResize);
        }

        componentWillUnmount() {
            window.removeEventListener('resize', this.windowResize);
        }

        render() {
            const menus = this.state.tree.map((node, index) => {
                if (!node.children || node.children.length <= 0) {
                return <Menu.Item key={node.id}><span id={node.id} onClick={this.doNodeClick}>{node.name}</span></Menu.Item>
                } else {
                    return this.createTreeMenu(node)
                }
            })
            return (
                <Layout width={'100%'}>
                    <Layout.Sider theme="light">
                        <div className="logo">菜单资源</div>
                        <Menu mode="inline">
                            {menus}
                        </Menu>
                    </Layout.Sider>
                    <Layout.Content>
                        <div className="form-title">资源信息</div>
                        <Form ref={this.resFormRefValue} style={{margin: 20}}>
                            <Row>
                                <Col span="11">
                                    <Form.Item label="资源ID" name="resourceid">
                                        <Input/>
                                    </Form.Item>
                                </Col>
                                <Col span="11">
                                    <Form.Item label="资源名称" name="cnname">
                                        <Input/>
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col span="11">
                                    <Form.Item label="资源URL" name="url">
                                        <Input/>
                                    </Form.Item>
                                </Col>
                                <Col span="11">
                                    <Form.Item label="上级资源ID" name="parentid">
                                        <Input/>
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col span="11">
                                    <Form.Item label="序号" name="orderid">
                                        <Input/>
                                    </Form.Item>
                                </Col>
                            </Row>
                            <div className="button-div">
                                <Button type="primary" onClick={this.doResAdd}>新增</Button>
                                <Button type="primary" onClick={this.doResUpdate}>修改</Button>
                                <Button type="primary" onClick={this.doResDelete}>删除</Button>
                            </div>
                        </Form>
                        <Modal
                            title={this.state.modelTitle}
                            visible={this.state.resShow}
                            onCancel={this.handleModelClose}
                            onOk={this.handleModelOk}
                            confirmLoading={this.state.loading}
                            destroyOnClose={false}
                            keyboard={false}
                            style={{top: 20}}
                            okText="确定"
                            cancelText="取消"
                            width={'100%'}>
                            <Form ref={this.resModelRefValue} labelCol={{span: 8}} wrapperCol={{span: 16}}>
                                <Row>
                                    <Col span="12">
                                        <Form.Item label="资源ID" name="resourceid"
                                                   rules={[{required: true, message: "请输入资源ID"}]}>
                                            <Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                        </Form.Item>
                                    </Col>
                                    <Col span="12">
                                        <Form.Item label="资源名称" name="cnname"
                                                   rules={[{required: true, message: "请输入资源ID"}]}>
                                            <Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                        </Form.Item>
                                    </Col>

                                    <Col span="12">
                                        <Form.Item label="资源URL" name="url"
                                                   rules={[{required: true, message: "请输入资源ID"}]}>
                                            <Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                        </Form.Item>
                                    </Col>
                                    <Col span="12">
                                        <Form.Item label="上级资源ID" name="parentid" rules={[{required: true, message: "请输入资源ID"}]}>
                                            <Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                        </Form.Item>
                                    </Col>
                                    <Col span="12">
                                        <Form.Item label="序号" name="orderid">
                                            <Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </Form>
                        </Modal>


                        <div className="form-title">资源操作</div>
                        <Table dataSource={this.state.list} bordered
                               onChange={(pagination)=>this.query(pagination.current)}
                               pagination={{ position: ["bottomLeft"],
                                   current: this.state.pageInfo.page,
                                   pageSize: this.state.pageInfo.size,
                                   total: this.state.pageInfo.total }}
                               rowSelection={{
                                   type: "radio",
                                   selectedRowKeys: this.state.selectedRowKeys,
                                   onChange: this.tableSelect
                               }}>
                            { /* Table columns 的语法 最终还是给 Table 传递 columns 参数 dataIndex 便是对象属性  */ }
                            <Table.Column title="操作ID" dataIndex="actid"></Table.Column>
                            <Table.Column title="资源ID" dataIndex="resourceid"></Table.Column>
                            <Table.Column title="操作描述" dataIndex="descr"></Table.Column>
                        </Table>
                        <div className="button-div">
                            <Button type="primary" onClick={this.doActAdd}>新增</Button>
                            <Button type="primary" onClick={this.doActUpdate}>修改</Button>
                            <Button type="primary" onClick={this.doActDelete}>删除</Button>
                        </div>
                        <Modal
                            title={this.state.modelTitle}
                            visible={this.state.actShow}
                            onCancel={this.handleModelClose}
                            onOk={this.handleModelOk}
                            confirmLoading={this.state.loading}
                            destroyOnClose={false}
                            keyboard={false}
                            style={{top: 20}}
                            okText="确定"
                            cancelText="取消"
                            width={'100%'}>
                            <Form ref={this.actModelRefValue} labelCol={{span: 8}} wrapperCol={{span: 16}}>
                                <Row>
                                    <Col span="12">
                                        <Form.Item label="操作ID" name="actid"
                                                   rules={[{required: true, message: "请输入资源ID"}]}>
                                            <Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                        </Form.Item>
                                    </Col>
                                    <Col span="12">
                                        <Form.Item label="操作描述" name="descr"
                                                   rules={[{required: true, message: "请输入资源ID"}]}>
                                            <Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                        </Form.Item>
                                    </Col>
                                    <Col span="12">
                                        <Form.Item label="资源ID" name="resourceid"
                                                   rules={[{required: true, message: "请输入资源ID"}]}>
                                            <Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </Form>
                        </Modal>

                    </Layout.Content>
                </Layout>
            )
        }
    }

    ReactDOM.render(
        <antd.ConfigProvider locale={antd.locales.zh_CN}>
            <Root/>
        </antd.ConfigProvider>,
        document.getElementById('app')
    );

</script>
</body>
</html>
